﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using StarkSDKSpace;
using System.Xml;
using System;
using Unity.VisualScripting;



public class GameController : MonoBehaviour, IPointerDownHandler, IDragHandler
{
    private GameCore core;
    private Text txtScore, txtRecord;
    private Transform bgTf;//背景变换组件 
    private RectTransform[,] bgTfArray;//背景图片的变换组件数组
    private AudioSource audioSource;
    public GameObject panelOver;
    public GameObject panelMain;
    public Text text;
    public Button SirBtn;
    public Button Opensir;
    public Text Sirtxt;
    private bool isLok=false;
    public Image FLPanel;
    public Button ZenjiafengshuBtn;
    public Button ZenjiaADStop;
    public GameObject ZengjiaAD;
    public GameObject ReturnBtnAD;
    private int[,] LastMap;
    public int LastScore;


    private string herovideoid = "142b8n320a6g515h77";
    private string zengjianfs = "162kedcoknq83pt63t";
    private string RenurnUpVideoId = "4g07had37cnd6fcnlv";
    private void Start()
    {
        core = new GameCore();
        //Screen.SetResolution(450, 590, false);
        
        screenFaderImage = UIManager.Instance.GetUIByName(NameManager.CANVAS, NameManager.SCREEN_FADER).GetComponent<Image>();
        bgTf = this.transform.Find(NameManager.BACKGROUND);
        txtScore = UIManager.Instance.GetUIByName(NameManager.PANEL_MAIN, NameManager.TXT_SCORE).GetComponent<Text>();
        txtRecord = UIManager.Instance.GetUIByName(NameManager.PANEL_MAIN, NameManager.TXT_RECORD).GetComponent<Text>();

        bgTfArray = new RectTransform[4, 4];
        spriteArray = new NumberSprite[4, 4];

        audioSource = this.GetComponent<AudioSource>();

        SetGridLayoutGroup();

        InitBackground();

        //加载最高分
        txtRecord.text = PlayerPrefs.GetInt("TopScore").ToString();

        Invoke("InitNewNumber", 0.4f);
    }
   




    /// <summary>
    /// 方格间隔
    /// </summary>
    public int interval = 15;
    //设置布局组
    private void SetGridLayoutGroup()
    {
        GridLayoutGroup grid = bgTf.GetComponent<GridLayoutGroup>();

        grid.padding = new RectOffset(interval, interval, interval, interval);
        float size = (this.GetComponent<RectTransform>().sizeDelta.x - 5 * interval) / 4;
        grid.cellSize = new Vector2(size, size);
        grid.spacing = new Vector2(interval, interval);
    }

    //初始化新数字
    private void InitNewNumber()
    {
        core.CalculateEmpty();//统计空位
        GenerateNumberSprite();
        GenerateNumberSprite();
    }

    //创建背景精灵
    private RectTransform CreateBackgroundSprite(Location loc)
    {
        GameObject spriteGo = new GameObject(loc.RIndex.ToString() + loc.CIndex);
        spriteGo.AddComponent<Image>().sprite = ResourceManager.GetImage(0);
        spriteGo.transform.SetParent(bgTf.transform, false);
        return spriteGo.GetComponent<RectTransform>();
    }

    //初始化  创建背景图片
    private void InitBackground()
    {
        for (int r = 0; r < 4; r++)
            for (int c = 0; c < 4; c++)
                bgTfArray[r, c] = CreateBackgroundSprite(new Location(r, c));
    }

    //创建数字精灵
    private NumberSprite CreateNumberSprite(Location loc, int number)
    {
        GameObject spriteObject = new GameObject("NumSprite");
        spriteObject.AddComponent<Image>();
        spriteObject.transform.SetParent(this.transform,false);
        NumberSprite script = spriteObject.AddComponent<NumberSprite>(); 
        script.Init(number, bgTfArray[loc.RIndex, loc.CIndex].position, bgTfArray[loc.RIndex, loc.CIndex].sizeDelta.x);
        return script;
    }

    //精灵数组
    private NumberSprite[,] spriteArray;
    //创建新数字精灵
    private void GenerateNumberSprite()
    {
        Location? loc;
        int? num;
        //生成新数
        core.GenerateNumber(out num, out loc);
        NumberSprite script = CreateNumberSprite(loc.Value, num.Value);
        //添加到精灵数组中
        spriteArray[loc.Value.RIndex, loc.Value.CIndex] = script;
        script.CreateEffect();
    }
     
    private void Update()
    {
    

        //如果地图有改变
        if (core.IsChange)
        {
            //SoundEffect();

            MoveEffects();

            ChangeMap();//修改地图

            DisplayScore();

            MergeEffects();

            GenerateNumberSprite();

            if (core.IsOver())
            {
                //panelOver.transform.position = new Vector3(225,295,0);
                panelOver.transform.position = panelMain.transform.position;
                panelOver.GetComponent<GameOverController>().Display();                              
            }
                
            core.IsChange = false;
        }
    }

 /*   private void SoundEffect()
    {
        audioSource.PlayOneShot(ResourceManager.GetSound("move"));

        if (core.MergeLocationList.Count > 0)
            audioSource.PlayOneShot(ResourceManager.GetSound("merge"));
    }*/

    //数字精灵移动效果
    private void MoveEffects()
    {
        for (int i = 0; i < core.MoveDataList.Count; i++)
        {
            //从核心类中获取需要移动的精灵位置
            MoveData data = core.MoveDataList[i];//包含原位置  目标位置

            //原位置精灵移动到目标位置的效果
            spriteArray[data.originalLoc.RIndex, data.originalLoc.CIndex].MoveEffect(bgTfArray[data.targetLoc.RIndex, data.targetLoc.CIndex].position);
            //将原位置引用复制到新位置中
            spriteArray[data.targetLoc.RIndex, data.targetLoc.CIndex] = spriteArray[data.originalLoc.RIndex, data.originalLoc.CIndex];//将当前位置图片精灵引用移动到上面0的位置
            //原位置引用清空
            spriteArray[data.originalLoc.RIndex, data.originalLoc.CIndex] = null;
        }
        ReturnBtnAD.SetActive(true);
    }

    //合并效果
    private void MergeEffects()
    { 
        for (int i = 0; i < core.MergeLocationList.Count; i++)
            spriteArray[core.MergeLocationList[i].RIndex, core.MergeLocationList[i].CIndex].MergeEffect();
    }

    //修改地图
    private void ChangeMap()
    {
        for (int r = 0; r < 4; r++)
        {
            for (int c = 0; c < 4; c++)
            {
                if (core.Map[r, c] == 0)
                {
                    if (spriteArray[r, c] != null)//如果地图为0  界面上该位置存在图片 则销毁
                        Destroy(spriteArray[r, c].gameObject);
                }
                else
                {
                    spriteArray[r, c].SetImage(core.Map[r, c]);
                }
            }
        }
    }

    public void DeepCopyMap(int[,] coreMap)
    {
        // 获取原数组的维度
        int rows = coreMap.GetLength(0);
        int cols = coreMap.GetLength(1);

        // 创建一个新的二维数组
        LastMap = new int[rows, cols];

        // 使用 Array.Copy 逐行复制数据（可以优化为一个循环）
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                LastMap[i, j] = coreMap[i, j];
            }
        }
    }

    private Vector2 beginPointer;
    private bool isDown = false;
    public void OnPointerDown(PointerEventData eventData)
    {
        beginPointer = eventData.position;
        isDown = true;
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (isDown == false) return;
        Vector2 touchOffset = eventData.position - beginPointer;

        MoveDirection? dir = null;
        if (Mathf.Abs(touchOffset.x) > Mathf.Abs(touchOffset.y) && Mathf.Abs(touchOffset.x) > 50)
        { //水平移动 
            dir = touchOffset.x > 0 ? MoveDirection.Right : MoveDirection.Left;
        }

        if (Mathf.Abs(touchOffset.x) < Mathf.Abs(touchOffset.y) && Mathf.Abs(touchOffset.y) > 50)
        { //垂直移动 
            dir = touchOffset.y > 0 ? MoveDirection.Up : MoveDirection.Down;
        }

        if (dir != null)
        {
            LastScore = core.Score;
            DeepCopyMap(core.Map);
            core.Move(dir.Value);
            isDown = false;
        }
    }

    public void Quit()
    {
        Application.Quit();
    }

    /// <summary>
    /// 重新开始
    /// </summary>
    public void Restart()
    {
        ClearSprite();
        txtScore.text = "0";
        core.Score = 0;
        core.ClearMap();
        ReturnBtnAD.SetActive(false);
        Invoke("InitNewNumber", 0.4f);
    }

    //清空所有UI数字精灵
    private void ClearSprite()
    {
        for (int i = 0; i < this.transform.childCount; i++)
        {
            if (this.transform.GetChild(i).name != "Background")
                Destroy(this.transform.GetChild(i).gameObject);
        }
    }

    //当脚本被销毁时
    private void OnDestroy()
    { //保存当前最高分 
        //如果记录大于成绩
        if (int.Parse(txtRecord.text) <= core.Score)
            PlayerPrefs.SetInt("TopScore", core.Score);
    }

    //显示成绩
    private void DisplayScore()
    {
        txtScore.text = core.Score.ToString();
        if (int.Parse(txtRecord.text) < core.Score)
            txtRecord.text = txtScore.text;
    }

    private Image screenFaderImage;
    private bool sceneStarting = true;
    private void StartScene()
    {
        screenFaderImage.color = Color.Lerp(screenFaderImage.color, Color.clear, Time.deltaTime);
        if (screenFaderImage.color.a <= 0.01f)
        {
            screenFaderImage.color = Color.clear;
            sceneStarting = false;
        }
    }

    public void Sidrot()
    {

        StarkSDKSpace.StarkSDK.API.GetStarkSideBarManager().NavigateToScene(StarkSideBar.SceneEnum.SideBar, () =>
        {
            //field1.text += "已通过侧边框返回";
        }, () => { }, (code, res) =>
        {
            //field3.text += $"navigate to scene error, errCode:{code}, errMsg:{res}";
        }
        );
        isLok = true;
       
        Sidbtn();
    }
    public void Sidbtn()
    {
        if (isLok)
        {
            
            Sirtxt.text = "已领取";
            core.Score +=100;
            DisplayScore();
            SirBtn.interactable = false;
            FLPanel.gameObject.SetActive(false);
        }

        
    }
    public void Opens()
    {
        FLPanel.gameObject.SetActive(true);

    }
    public void Stops()
    {
        FLPanel.gameObject.SetActive(false);
    }
    //public void GuainBtnClick()
    //{
    //    StarkSDK.API.GetStarkAdManager().ShowVideoAdWithId(herovideoid,
    //     (bComplete) =>
    //     {
    //         if (bComplete)
    //         { ReGegin(); MaidianNew.MaidianBackCallback(" "); }
    //         else
    //         { gameObject.SetActive(true); };
    //     },
    //     OnAdError, null);
    //}

    public void GuainBtnClick()
    {
        TTSDK.TTRewardedVideoAd r = AdMgr.Instance.ShowVideoAdNew(herovideoid);

        //创建激励视频关闭回调
        r.OnClose += (bol, val) =>
        {
            Debug.Log("关闭广告 ，是否已经看完" + bol);
            //看完广告获得提示
            if (bol)
            {
                ReGegin(); 
                MaidianNew.MaidianBackCallback(" ");
                Debug.Log("广告看完");
            }
            else
            {
                gameObject.SetActive(true);
                Debug.Log("广告未看完");
            }
        };

        //创建报错回调  
        r.OnError += (code, errorMessage) =>
        {

            Debug.Log("code:" + code + "错误信息：" + errorMessage);
        };

        //展示广告（新版本必须调用，不然无法展示出来广告）
        r.Show();

    }

    //public void ZJFS()
    //{
    //    StarkSDK.API.GetStarkAdManager().ShowVideoAdWithId(zengjianfs,
    //     (bComplete) =>
    //     {
    //         if (bComplete)
    //         {
    //             core.Score += 500;
    //             MaidianNew.MaidianBackCallback(" ");
    //             Debug.Log("zhengjia500");
    //             StopZJAD();
    //         }
    //         else
    //         { gameObject.SetActive(true); };
    //     },
    //     OnAdError, null);
    //}

    public void ZJFS()
    {
        TTSDK.TTRewardedVideoAd r = AdMgr.Instance.ShowVideoAdNew(zengjianfs);

        //创建激励视频关闭回调
        r.OnClose += (bol, val) =>
        {
            Debug.Log("关闭广告 ，是否已经看完" + bol);
            //看完广告获得提示
            if (bol)
            {
                core.Score += 500;
                DisplayScore();
                MaidianNew.MaidianBackCallback(" ");
                Debug.Log("zhengjia500");
                StopZJAD();
                Debug.Log("广告看完");
            }
            else
            {
                gameObject.SetActive(true);
                Debug.Log("广告未看完");
            }
        };

        //创建报错回调  
        r.OnError += (code, errorMessage) =>
        {

            Debug.Log("code:" + code + "错误信息：" + errorMessage);
        };

        //展示广告（新版本必须调用，不然无法展示出来广告）
        r.Show();

    }

    //public void Return()
    //{

    //    StarkSDK.API.GetStarkAdManager().ShowVideoAdWithId(zengjianfs,
    //     (bComplete) =>
    //     {
    //         if (bComplete)
    //         {
    //             Undo();
    //             MaidianNew.MaidianBackCallback(" ");
    //             Debug.Log("Return last");
    //         }
    //         else
    //         { gameObject.SetActive(true); }
    //         ;
    //     },
    //     OnAdError, null);
    //}

    public void Return()
    {
        TTSDK.TTRewardedVideoAd r = AdMgr.Instance.ShowVideoAdNew(RenurnUpVideoId);

        //创建激励视频关闭回调
        r.OnClose += (bol, val) =>
        {
            Debug.Log("关闭广告 ，是否已经看完" + bol);
            //看完广告获得提示
            if (bol)
            {
                Undo();
                MaidianNew.MaidianBackCallback(" ");
                Debug.Log("广告看完");
            }
            else
            {
                gameObject.SetActive(true);
                Debug.Log("广告未看完");
            }
        };

        //创建报错回调  
        r.OnError += (code, errorMessage) =>
        {

            Debug.Log("code:" + code + "错误信息：" + errorMessage);
        };

        //展示广告（新版本必须调用，不然无法展示出来广告）
        r.Show();

    }
    public void ZJAD() { ZengjiaAD.SetActive(true); }
    public void StopZJAD() { ZengjiaAD.SetActive(false); }
    void OnAdError(int iErrCode, string errMsg)
    {
        Debug.Log("错误 ： " + iErrCode + "  " + errMsg);
    }
    public void ReGegin()
    {
        ClearSprite();       
        core.ClearMap();
        ReturnBtnAD.SetActive(false);
        Invoke("InitNewNumber", 0.4f);
       
    }
    // 实现撤销功能的方法
    public void Undo()
    {
        // 假设 temporaryLastMap 存储的是符合条件的 (r, c) 坐标对
        List<(int, int)> temporaryLastMap = new List<(int, int)>();
        ClearSprite();
        core.ClearMap();
        core.Map = LastMap;
        core.Score = LastScore;
        txtScore.text = core.Score.ToString();
        Array.Clear(spriteArray, 0, spriteArray.Length);
        for (int r = 0; r < 4; r++)
        {
            for (int c = 0; c < 4; c++)
            {
                if (LastMap[r, c] != 0)
                {
                    temporaryLastMap.Add((r, c));
                }
            }
        }
        for (int i = 0; i < temporaryLastMap.Count; i++)
        {
            core.GenerateReturnNumber(LastMap[temporaryLastMap[i].Item1, temporaryLastMap[i].Item2], new Location(temporaryLastMap[i].Item1, temporaryLastMap[i].Item2));
            NumberSprite script = CreateNumberSprite(new Location(temporaryLastMap[i].Item1, temporaryLastMap[i].Item2), LastMap[temporaryLastMap[i].Item1, temporaryLastMap[i].Item2]);
            //添加到精灵数组中
            spriteArray[temporaryLastMap[i].Item1, temporaryLastMap[i].Item2] = script;
            script.CreateEffect();
        }
        ReturnBtnAD.SetActive(false);
    }
}



